<template>
  <el-card class="mt-20 mr-20" shadow="never">
    <el-form ref="formRef" :rules="rules" :model="form" label-position="top">
      <el-table :data="form.userArr" :header-cell-style="tableHeadStyle">
        <el-table-column :label="$t('pageStr.indexStr')" align="center" width="50">
          <template #default="scope">
            <div>{{ scope.$index + 1 }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div><span class="text-error">*</span>{{ $t('pageStr.userNameStr') }}</div>
          </template
          >
          <template #default="{row}">
            <el-input :disabled="row.exist" v-model="row.uname" style="width: 95%" clearable/>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div><span class="text-error">*</span>{{ $t('pwd') }}</div>
          </template>
          <template #default="{row}">
            <el-input v-model="row.password" type="password" show-password :placeholder="row.exist ? '******' : ''"
                      style="width: 95%" clearable/>
          </template>
        </el-table-column>
        <el-table-column align="center">
          <template #header>
            <div><span class="text-error">*</span>{{ $t('pageStr.authLevelStr') }}</div>
          </template>
          <template #default="{row, $index}">
            <el-select v-model="row.level" style="width: 95%">
              <el-option v-for="item of authArr" :label="item.label" :value="item.level"/>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column :label="$t('pageStr.operationStr')" align="center" width="80">
          <template #default="{$index}">
            <div class="flex flex-center">
              <div>{{ $t('pageStr.sureStr') }}</div>
              <img src="@/assets/icon/sure.png" class="removeIcon pointer" @click="handleSure($index)">
            </div>
          </template>
        </el-table-column>
        <el-table-column width="80" align="center">
          <template #default="scope">
            <div class="flex flex-center">
              <img v-if="form.userArr.length > 1" @click="handleRemoveRow(scope.$index)"
                   src="@/assets/icon/remove.png" class="removeIcon pointer">
              <img v-if="form.userArr.length < 10" @click="handleAddRow(scope.$index)" src="@/assets/icon/add.png"
                   class="removeIcon pointer">
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
  </el-card>
</template>

<script setup>
import {ref, onBeforeMount} from 'vue'
import {reqSetUsers, reqGetUsers, reqAddUsers, reqDelUsers} from '@/api/users/user-manage'
import {ElMessage} from "element-plus";
import {useI18n} from 'vue-i18n'
import {encrypt, decrypt} from '@/utils'

const formRef = ref(null)
const {t} = useI18n()
const rules = {
  level: [{required: true, message: t('emptyTip'), trigger: 'blur'}],
  ip: [{required: true, message: t('emptyTip'), trigger: 'blur'}],
  port: [{required: true, message: t('emptyTip'), trigger: 'blur'}],
  data: [{required: true, message: t('emptyTip'), trigger: 'blur'}],
}
const authArr = [{label: '只读', level: '1'}, {label: '读写', level: '2'}]
const form = ref({
  userArr: [{}]
})

onBeforeMount(getData)

function getData() {
  reqGetUsers().then((res) => {
    // 获取用户列表，剔除包含admin的用户
    form.value.userArr = res.usersGet.filter((item) => {
      return item.uname !== 'admin'
    })
    form.value.userArr.forEach((item) => {
      item.exist = true
    })
    console.log('读取用户信息', form.value)
  })
}

// table表头的样式
const tableHeadStyle = {
  'text-align': 'center',
  'background-color': '#F5EFE9',
  'max-width': '1000px'
}

function handleRemoveRow(index) {
  const delUname = form.value.userArr[index].uname
  console.log('移除', index, delUname)
  if (form.value.userArr[index].exist) {
    reqDelUsers({uname: delUname}).then(() => {
      ElMessage.success(t('successTip'))
      getData()
    }).catch(() => {
      ElMessage.error(t('errorTip'))
    })
    //删除的不存在
  } else {
    console.log('删除的不存在')
    form.value.userArr.splice(index,1)
  }
}

/**
 * 点击确认
 * @param index
 */
function handleSure(index) {
  formRef.value.validate((valid) => {
    if (!valid) {
      return
    }
    const submitForm = form.value.userArr[index]
    console.log('确认', index, submitForm)
    if (submitForm.exist) {
      updateUser(submitForm)
    } else {
      addUser(submitForm)
    }
  })

}

/**
 * 添加用户
 * @param data
 */
function addUser(data) {
  console.log('添加用户', data)
  if (!data.uname || !data.password || !data.level) {
    ElMessage.error(t('emptyTip'))
    return
  }
  data.password = encrypt(data.password)
  reqAddUsers(data).then((res) => {
    if (res.userAdd == 0) {
      ElMessage.success(t('successTip'))
    } else {
      ElMessage.error(t('errorTip'))
    }
    getData()
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

/**
 * 更新用户
 * @param data
 */
function updateUser(data) {
  console.log('修改用户', data)
  if (!data.level) {
    ElMessage.error(t('emptyTip'))
    return
  }
  data.password = encrypt(data.password)
  reqSetUsers(data).then((res) => {
    if (res.userChg == 0) {
      ElMessage.success(t('successTip'))
    } else {
      ElMessage.error(t('errorTip'))
    }
    getData()
  }).catch(() => {
    ElMessage.error(t('errorTip'))
  })
}

function handleAddRow(index) {
  // 在数组指定下标插入指定元素
  form.value.userArr.splice(index + 1, 0, {level: '1'})
}

</script>

<style scoped>
.addBtn {
  margin-top: 10px;
  width: 1050px;
}

.removeIcon {
  width: 20px;
  height: 20px;
  margin-right: 10px;
}
</style>